package com.vito.oa.act.extend.service.impl;

import static com.vito.oa.act.constant.OaActContants.CACHE_ACT_VALUE;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.activiti.engine.repository.Deployment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;

import com.alibaba.dubbo.config.annotation.Service;
import com.vito.act.approval.model.ActApprovalProgressModel;
import com.vito.act.approval.service.impl.ActApprovalProgressServiceImpl;
import com.vito.act.model.ActExBussDefModel;
import com.vito.act.model.ActExBussModel;
import com.vito.act.model.BpmnProcess;
import com.vito.act.model.BpmnUserTask;
import com.vito.act.tool.ActivitiOper;
import com.vito.act.tool.ActivitiTool;
import com.vito.base.authoriza.dao.CreateIdMapper;
import com.vito.base.model.DataGrid;
import com.vito.base.model.MyHashMap;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.util.Contants;
import com.vito.base.util.Validata;
import com.vito.oa.act.constant.OaActContants;
import com.vito.oa.act.dao.ActUserProcessSettingMapper;
import com.vito.oa.act.dao.OaActProcessMapper;
import com.vito.oa.act.extend.dao.OaActApprovalProgressMapper;
import com.vito.oa.act.extend.dao.OaActExApproveInfoMapper;
import com.vito.oa.act.extend.dao.OaActExBussDefMapper;
import com.vito.oa.act.extend.dao.OaActExBussMapper;
import com.vito.oa.act.extend.model.OaActExBussDefModel;
import com.vito.oa.act.extend.model.OaActExBussModel;
import com.vito.oa.act.extend.model.OaBpmnProcess;
import com.vito.oa.act.extend.service.OaActApprovalFormService;
import com.vito.oa.act.extend.service.OaActApprovalProgressService;
import com.vito.oa.act.model.ActUserNodeSettingModel;
import com.vito.oa.act.model.ActUserProcessSettingModel;
import com.vito.oa.act.model.ProcessCopyLogModel;

@Service
public class OaActApprovalProgressServiceImpl extends ActApprovalProgressServiceImpl implements OaActApprovalProgressService{
	private static final Logger log = LoggerFactory.getLogger(OaActApprovalProgressServiceImpl.class);
	@Autowired
	private OaActApprovalProgressMapper actApprovalProgressMapper;
	@Autowired
	private OaActExApproveInfoMapper actExApproveInfoMapper;
	@Autowired
	private CreateIdMapper createIdMapper;
	@Autowired 
	private OaActProcessMapper oaActProcessMapper;
	@Autowired 
	private OaActExBussMapper oaActExBussMapper;
	@Autowired
	private OaActApprovalFormService actApprovalFormService;
	@Autowired
	private ActUserProcessSettingMapper actUserProcessSettingMapper;
	@Autowired 
	private OaActExBussDefMapper oaActExBussDefMapper;

	@Override
	public DataGrid<MyHashMap<String, String>> queryProgressByPage(OaActExBussModel model) {
		DataGrid<MyHashMap<String, String>> data = new DataGrid<MyHashMap<String, String>>();
			data.setRows(actApprovalProgressMapper.queryProgress(model));
			data.setTotal(actApprovalProgressMapper.queryProgressCount(model));
			return data;
	}
	
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public Result addProgress(OaActExBussModel model) {
		Result r = new Result();
		try {
			model.setPhoneStatus(OaActContants.BASE_STATE);
			model.setIsDefined(OaActContants.BASE_STATE);
			model.setTotalTimeLimit(0);
			if(!Validata.isNullOrEmpty(model.getProcessKey())){
				if(actExApproveInfoMapper.queryProcessDataCount(model.getProcessKey())==0){
					//删除工作流
					ActivitiOper.undeployByKey(model.getProcessKey());
				}else{
					r.setCode(Result.CODE_PARA_ERROR);
					r.setMsg("流程“"+model.getBusinessName()+"”已使用，系统不支持修改");
					return r;
				}
			}
			String processKey = Contants.PROCESS_HEAD+createIdMapper.getId("processKey");
			//创建一个流程
			BpmnProcess bpmnProcess = new OaBpmnProcess(processKey, model.getBusinessName());
			//取得用户添加流程节点
			LinkedList<OaActExBussDefModel> nodes = model.getNodes();
			if(!nodes.isEmpty()){
				int i=1;
				String processNodeKey = null;
				for(OaActExBussDefModel node : nodes){
					processNodeKey = Contants.PROCESS_NODE_HEAD+String.valueOf(i);
					node.setProcessKey(processKey);
					node.setProcessNodeId(processNodeKey);
					node.setOrdernum(i);
					node.setRefKey(Contants.COMM_FORM_ID);
					//工作流创建节点
					BpmnUserTask task = new BpmnUserTask(node.getProcessNodeName());
					task.setId(processNodeKey);
					if(i==nodes.size()){
						bpmnProcess =  bpmnProcess.addUserTask(task).endTask();
					}else{
						bpmnProcess.addUserTask(task);
					}
					i++;
				}
				//new开始节点
				OaActExBussDefModel startNode = new OaActExBussDefModel();
				startNode.setProcessNodeId(OaActContants.FORM_PROCESS_START);
				startNode.setProcessNodeName(OaActContants.FORM_PROCESS_STARTNAME);
				startNode.setProcessKey(processKey);
				startNode.setRefKey(model.getFormId());
				startNode.setOrdernum(0);
				nodes.addFirst(startNode);
			}
				String id = ActivitiOper.deploy(bpmnProcess);
				if(Validata.isNullOrEmpty(id)){
					log.error("============用户自定义流程，创建bpmn失败===============");
					r.setCode(Result.CODE_ERROR);
					r.setMsg("创建失败，请稍后再试");
				}
				model.setBusinessId(id);
				model.setProcessKey(processKey);
				actApprovalProgressMapper.saveProgressNode(nodes);
				actApprovalProgressMapper.saveProgress(model);
				
				OaActExBussModel eexModel = new OaActExBussModel();
				eexModel.setProcessKey(model.getProcessKey());
				eexModel.setMoudelType(OaActContants.PROCESS_MOUDEL_TYPE_APPROVAL);
				oaActExBussMapper.saveActEExBuss(eexModel);
				
				r.setData(processKey);
				r.setCode(Result.CODE_OK);
				r.setMsg(ResMsg.SAVESUC);
		} catch (Exception e) {
			log.error("添加流程异常：",e);
			r.setCode(Result.CODE_ERROR);
			r.setMsg(ResMsg.EXECERR);
			return r;
		}
		return r;
	}

	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public int updateProgressStatus(Map<String, String> map) {
		return actApprovalProgressMapper.updateProgressStatus(map);
	}
	
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public int updateProgressOrder(List<Map<String, String>> list,String dept_id,String user_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dept_id", dept_id);
		map.put("operuser", user_id);
		map.put("items", list);
		return actApprovalProgressMapper.updateProgressOrder(map);
 	}
	
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public Result deleteProgress(ActExBussModel bussModel) {
		Result r = new Result();
		String deptId = bussModel.getCreateDept();
		String key = bussModel.getProcessKey();

		bussModel = oaActExBussMapper.queryActExBussByProcessKey(bussModel);
		if(bussModel == null){
			r.setMsg("流程不存在");
			r.setCode(Result.CODE_PARA_ERROR);
			return r;
		}
		if(actExApproveInfoMapper.queryProcessStatus(bussModel) == 0){
			if(Contants.FORM_BUSENESS_SYS_DEPT.equals(bussModel.getCreateDept())){
				//只从企业移除该流程
				bussModel.setCreateDept(deptId);
				oaActExBussMapper.deleteExUserBuss(bussModel);
				actUserProcessSettingMapper.deleteAllUserSetting(key, deptId);
				r.setCode(Result.CODE_OK);
				r.setMsg(ResMsg.DELSUC);
				return r;
			}else{
				if(actExApproveInfoMapper.queryRunningDataCount(bussModel) ==0){
					//判断流程是否为导入模板，是则删除导入记录
					ProcessCopyLogModel copyModel = oaActProcessMapper.queryImportLog(bussModel.getBusinessId());
					if(copyModel != null){
						String formId= copyModel.getNewFormId();						
						oaActProcessMapper.deleteImportLog(copyModel.getCopyId());
						if(Validata.notNullOrEmpty(formId)){
							actApprovalFormService.deleteForm(formId);
						}
					}
					//卸载流程
					List<Deployment> list = ActivitiTool.getRepositoryServiceImpl().createDeploymentQuery()
							.processDefinitionKey(bussModel.getProcessKey()).list();
					if(list != null && list.size() >0){
						for(Deployment dep : list){
							ActivitiOper.undeployByDeploymentId(dep.getId());
						}
					}
					//删除相关表信息
					actApprovalProgressMapper.deleteProgress(bussModel.getProcessKey());
					//删除用户配置信息
					actUserProcessSettingMapper.deleteAllUserSetting(key, deptId);
					r.setCode(Result.CODE_OK);
					r.setMsg(ResMsg.DELSUC);
				}else{
					r.setCode(Result.CODE_PARA_ERROR);
					r.setMsg("存在未完结的流程，无法删除");
				}
			}
		}else{
			r.setCode(Result.CODE_PARA_ERROR);
			r.setMsg("流程启用中，无法删除");
		}
		return r;
	}
	
	@Override
	@CacheEvict(value=CACHE_ACT_VALUE,allEntries=true)
	public int updateProgressBaseMsg(ActApprovalProgressModel model) {
		return actApprovalProgressMapper.updateProgressBaseMsg(model);
	}
	
	@Override
	public void addProcessToCompany(ActUserProcessSettingModel processSetting,String operUser) {
		String key = processSetting.getProcess().getProcessKey();
		if(key != null){
			String companyId = processSetting.getCompanyId();
			Map<String,String> parame = new HashMap<String,String>();
			parame.put("deptId", companyId);
			parame.put("operUser", operUser);
			//parame.put("processKey", processSetting.getProcessKey());
			parame.put("processKey",key);
			parame.put("status", "0");
			actApprovalProgressMapper.addProcessToCompany(parame);
			
			//流程与企业建立关系后，初始化企业对该流程及节点的配置
			actUserProcessSettingMapper.saveProcessSetting(processSetting);
			
			List<ActUserNodeSettingModel> settingList = processSetting.getNodeSetting();
			if(settingList == null){
				settingList = new ArrayList<>();
				ActExBussDefModel bussModel = new ActExBussDefModel();
				bussModel.setProcessKey(key);
				List<OaActExBussDefModel> nodes = oaActExBussDefMapper.queryActExBussDefByPage(bussModel);
				   
				ActUserNodeSettingModel nodeSetting = null;
				for(OaActExBussDefModel node : nodes){
					nodeSetting = new ActUserNodeSettingModel();
					nodeSetting.setCompanyId(companyId);
					nodeSetting.setNode(node);
					nodeSetting.setNodeName(node.getProcessNodeName());
					nodeSetting.setIsSeal("0");
					nodeSetting.setIsSeal("0");
					nodeSetting.setMarkOfApproved("同意");
					nodeSetting.setMarkOfApproving("审批中");
					nodeSetting.setMarkOfWait("待审批");
					settingList.add(nodeSetting);
				}
			}	
			actUserProcessSettingMapper.saveAllNodesSetting(settingList);
		}
	}
}
